package com.ruoyi.campus.controller;

import com.ruoyi.campus.domain.UserExtend;
import com.ruoyi.campus.service.IUserExtendService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.common.core.domain.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 小程序用户管理控制器
 * 供后台管理员统一管理小程序用户
 * 
 * @author campus-alarm
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/campus/miniprogram/users")
public class MiniProgramUserManageController extends BaseController {

    @Autowired
    private IUserExtendService userExtendService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询小程序用户列表
     */
    @PreAuthorize("@ss.hasPermi('campus:miniuser:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserExtend userExtend) {
        startPage();
        List<UserExtend> list = userExtendService.selectUserExtendList(userExtend);
        return getDataTable(list);
    }

    /**
     * 查询小程序用户详细信息
     */
    @PreAuthorize("@ss.hasPermi('campus:miniuser:query')")
    @GetMapping("/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId) {
        try {
            // 获取系统用户信息
            SysUser sysUser = sysUserService.selectUserById(userId);
            if (sysUser == null) {
                return AjaxResult.error("用户不存在");
            }

            // 获取扩展信息
            UserExtend userExtend = userExtendService.selectUserExtendByUserId(userId);
            
            // 组装详细信息
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("sysUser", sysUser);
            userInfo.put("userExtend", userExtend);
            
            return AjaxResult.success(userInfo);
        } catch (Exception e) {
            logger.error("获取小程序用户详情失败", e);
            return AjaxResult.error("获取用户详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增小程序用户
     */
    @PreAuthorize("@ss.hasPermi('campus:miniuser:add')")
    @Log(title = "小程序用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Map<String, Object> userData) {
        try {
            // 提取系统用户信息
            Map<String, Object> sysUserData = (Map<String, Object>) userData.get("sysUser");
            Map<String, Object> userExtendData = (Map<String, Object>) userData.get("userExtend");

            // 创建系统用户
            SysUser sysUser = new SysUser();
            sysUser.setUserName((String) sysUserData.get("userName"));
            sysUser.setNickName((String) sysUserData.get("nickName"));
            sysUser.setEmail((String) sysUserData.get("email"));
            sysUser.setPhonenumber((String) sysUserData.get("phonenumber"));
            sysUser.setSex((String) sysUserData.get("sex"));
            sysUser.setPassword((String) sysUserData.get("password"));
            sysUser.setStatus("0"); // 默认启用
            sysUser.setCreateBy(getUsername());

            int result = sysUserService.insertUser(sysUser);
            if (result > 0 && userExtendData != null) {
                // 创建扩展信息
                UserExtend userExtend = new UserExtend();
                userExtend.setUserId(sysUser.getUserId());
                userExtend.setSchoolId(getLongValue(userExtendData.get("schoolId")));
                userExtend.setClassId(getLongValue(userExtendData.get("classId")));
                userExtend.setUserType(getIntegerValue(userExtendData.get("userType")));
                userExtend.setStudentNumber((String) userExtendData.get("studentNumber"));
                userExtend.setTeacherNumber((String) userExtendData.get("teacherNumber"));
                userExtend.setWechatOpenid((String) userExtendData.get("wechatOpenid"));
                userExtend.setGender(getIntegerValue(userExtendData.get("gender")));

                userExtendService.insertUserExtend(userExtend);
            }

            return toAjax(result);
        } catch (Exception e) {
            logger.error("新增小程序用户失败", e);
            return AjaxResult.error("新增用户失败：" + e.getMessage());
        }
    }

    /**
     * 修改小程序用户
     */
    @PreAuthorize("@ss.hasPermi('campus:miniuser:edit')")
    @Log(title = "小程序用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Map<String, Object> userData) {
        try {
            Map<String, Object> sysUserData = (Map<String, Object>) userData.get("sysUser");
            Map<String, Object> userExtendData = (Map<String, Object>) userData.get("userExtend");

            // 更新系统用户
            SysUser sysUser = new SysUser();
            sysUser.setUserId(getLongValue(sysUserData.get("userId")));
            sysUser.setNickName((String) sysUserData.get("nickName"));
            sysUser.setEmail((String) sysUserData.get("email"));
            sysUser.setPhonenumber((String) sysUserData.get("phonenumber"));
            sysUser.setSex((String) sysUserData.get("sex"));
            sysUser.setStatus((String) sysUserData.get("status"));
            sysUser.setUpdateBy(getUsername());

            int result = sysUserService.updateUser(sysUser);
            if (result > 0 && userExtendData != null) {
                // 更新扩展信息
                UserExtend userExtend = new UserExtend();
                userExtend.setUserId(sysUser.getUserId());
                userExtend.setSchoolId(getLongValue(userExtendData.get("schoolId")));
                userExtend.setClassId(getLongValue(userExtendData.get("classId")));
                userExtend.setUserType(getIntegerValue(userExtendData.get("userType")));
                userExtend.setStudentNumber((String) userExtendData.get("studentNumber"));
                userExtend.setTeacherNumber((String) userExtendData.get("teacherNumber"));
                userExtend.setWechatOpenid((String) userExtendData.get("wechatOpenid"));
                userExtend.setGender(getIntegerValue(userExtendData.get("gender")));

                userExtendService.updateUserExtend(userExtend);
            }

            return toAjax(result);
        } catch (Exception e) {
            logger.error("修改小程序用户失败", e);
            return AjaxResult.error("修改用户失败：" + e.getMessage());
        }
    }

    /**
     * 删除小程序用户
     */
    @PreAuthorize("@ss.hasPermi('campus:miniuser:remove')")
    @Log(title = "小程序用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        try {
            for (Long userId : userIds) {
                // 删除扩展信息
                userExtendService.deleteUserExtendByUserId(userId);
                // 删除系统用户
                sysUserService.deleteUserById(userId);
            }
            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            logger.error("删除小程序用户失败", e);
            return AjaxResult.error("删除用户失败：" + e.getMessage());
        }
    }

    /**
     * 重置用户密码
     */
    @PreAuthorize("@ss.hasPermi('campus:miniuser:resetPwd')")
    @Log(title = "小程序用户", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody Map<String, Object> request) {
        try {
            Long userId = getLongValue(request.get("userId"));
            String newPassword = (String) request.get("newPassword");

            SysUser user = new SysUser();
            user.setUserId(userId);
            user.setPassword(newPassword);
            user.setUpdateBy(getUsername());

            SysUser sysUser = sysUserService.selectUserById(userId);
            return toAjax(sysUserService.resetUserPwd(sysUser.getUserName(), newPassword));
        } catch (Exception e) {
            logger.error("重置密码失败", e);
            return AjaxResult.error("重置密码失败：" + e.getMessage());
        }
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('campus:miniuser:edit')")
    @Log(title = "小程序用户", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody Map<String, Object> request) {
        try {
            Long userId = getLongValue(request.get("userId"));
            String status = (String) request.get("status");

            SysUser user = new SysUser();
            user.setUserId(userId);
            user.setStatus(status);
            user.setUpdateBy(getUsername());

            return toAjax(sysUserService.updateUserStatus(user));
        } catch (Exception e) {
            logger.error("修改用户状态失败", e);
            return AjaxResult.error("修改状态失败：" + e.getMessage());
        }
    }

    /**
     * 批量操作
     */
    @PreAuthorize("@ss.hasPermi('campus:miniuser:edit')")
    @Log(title = "小程序用户批量操作", businessType = BusinessType.UPDATE)
    @PutMapping("/batchOperation")
    public AjaxResult batchOperation(@RequestBody Map<String, Object> request) {
        try {
            String operation = (String) request.get("operation");
            Long[] userIds = convertToLongArray(request.get("userIds"));
            
            int successCount = 0;
            for (Long userId : userIds) {
                switch (operation) {
                    case "enable":
                        // 启用用户
                        SysUser enableUser = new SysUser();
                        enableUser.setUserId(userId);
                        enableUser.setStatus("0");
                        enableUser.setUpdateBy(getUsername());
                        sysUserService.updateUserStatus(enableUser);
                        successCount++;
                        break;
                    case "disable":
                        // 停用用户
                        SysUser disableUser = new SysUser();
                        disableUser.setUserId(userId);
                        disableUser.setStatus("1");
                        disableUser.setUpdateBy(getUsername());
                        sysUserService.updateUserStatus(disableUser);
                        successCount++;
                        break;
                    case "resetPwd":
                        // 重置密码为默认密码
                        SysUser resetUser = new SysUser();
                        resetUser.setUserId(userId);
                        resetUser.setPassword("admin123");
                        resetUser.setUpdateBy(getUsername());
                        SysUser userInfo = sysUserService.selectUserById(userId);
                        sysUserService.resetUserPwd(userInfo.getUserName(), "admin123");
                        successCount++;
                        break;
                }
            }
            
            return AjaxResult.success("批量操作成功，处理了 " + successCount + " 个用户");
        } catch (Exception e) {
            logger.error("批量操作失败", e);
            return AjaxResult.error("批量操作失败：" + e.getMessage());
        }
    }

    /**
     * 获取小程序用户统计信息
     */
    @PreAuthorize("@ss.hasPermi('campus:miniuser:list')")
    @GetMapping("/statistics")
    public AjaxResult getStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 总用户数
            UserExtend queryAll = new UserExtend();
            List<UserExtend> allUsers = userExtendService.selectUserExtendList(queryAll);
            statistics.put("totalUsers", allUsers.size());
            
            // 按用户类型统计
            Map<String, Integer> userTypeStats = new HashMap<>();
            userTypeStats.put("students", 0);  // 学生
            userTypeStats.put("teachers", 0);  // 教师
            userTypeStats.put("parents", 0);   // 家长
            userTypeStats.put("admins", 0);    // 管理员
            
            // 按状态统计
            Map<String, Integer> statusStats = new HashMap<>();
            statusStats.put("active", 0);    // 启用
            statusStats.put("inactive", 0);  // 停用
            
            for (UserExtend user : allUsers) {
                // 统计用户类型
                switch (user.getUserType()) {
                    case 1:
                        userTypeStats.put("students", userTypeStats.get("students") + 1);
                        break;
                    case 2:
                        userTypeStats.put("teachers", userTypeStats.get("teachers") + 1);
                        break;
                    case 3:
                        userTypeStats.put("parents", userTypeStats.get("parents") + 1);
                        break;
                    case 4:
                        userTypeStats.put("admins", userTypeStats.get("admins") + 1);
                        break;
                }
                
                // 统计状态（需要查询系统用户表）
                SysUser sysUser = sysUserService.selectUserById(user.getUserId());
                if (sysUser != null) {
                    if ("0".equals(sysUser.getStatus())) {
                        statusStats.put("active", statusStats.get("active") + 1);
                    } else {
                        statusStats.put("inactive", statusStats.get("inactive") + 1);
                    }
                }
            }
            
            statistics.put("userTypeStats", userTypeStats);
            statistics.put("statusStats", statusStats);
            
            return AjaxResult.success(statistics);
        } catch (Exception e) {
            logger.error("获取统计信息失败", e);
            return AjaxResult.error("获取统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 导出小程序用户列表
     */
    @PreAuthorize("@ss.hasPermi('campus:miniuser:export')")
    @Log(title = "小程序用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UserExtend userExtend) {
        List<UserExtend> list = userExtendService.selectUserExtendList(userExtend);
        ExcelUtil<UserExtend> util = new ExcelUtil<UserExtend>(UserExtend.class);
        util.exportExcel(response, list, "小程序用户数据");
    }

    // 辅助方法
    private Long getLongValue(Object value) {
        if (value == null) return null;
        if (value instanceof Long) return (Long) value;
        if (value instanceof Integer) return ((Integer) value).longValue();
        if (value instanceof String) return Long.parseLong((String) value);
        return null;
    }

    private Integer getIntegerValue(Object value) {
        if (value == null) return null;
        if (value instanceof Integer) return (Integer) value;
        if (value instanceof Long) return ((Long) value).intValue();
        if (value instanceof String) return Integer.parseInt((String) value);
        return null;
    }

    private Long[] convertToLongArray(Object value) {
        if (value instanceof List) {
            List<?> list = (List<?>) value;
            return list.stream().map(item -> getLongValue(item)).toArray(Long[]::new);
        }
        return new Long[0];
    }
} 